import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface CartItem {
  productId: number;
  name: string;
  price: number;
  quantity: number;
  imageUrl: string;
  description: string;
  paramList?: Array<{
    paramValueId: number;
    paramValueName: string;
  }>;
}

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const cartItems = ref<CartItem[]>([]);
  
  // 当前选中的门店
  const currentStore = ref<any>(null);

  // 计算购物车商品总数
  const totalItems = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0);
  });

  // 计算购物车总金额
  const totalAmount = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0);
  });

  // 添加商品到购物车
  const addToCart = (item: CartItem) => {
    const existingItem = cartItems.value.find(i => i.productId === item.productId);
    if (existingItem) {
      existingItem.quantity += item.quantity;
    } else {
      cartItems.value.push(item);
    }
  };

  // 从购物车移除商品
  const removeFromCart = (productId: number) => {
    const index = cartItems.value.findIndex(item => item.productId === productId);
    if (index > -1) {
      cartItems.value.splice(index, 1);
    }
  };

  // 更新购物车商品数量
  const updateQuantity = (productId: number, quantity: number) => {
    const item = cartItems.value.find(item => item.productId === productId);
    if (item) {
      item.quantity = quantity;
    }
  };

  // 清空购物车
  const clearCart = () => {
    cartItems.value = [];
  };

  // 设置当前门店
  const setCurrentStore = (store: any) => {
    currentStore.value = store;
  };

  // 清空当前门店
  const clearCurrentStore = () => {
    currentStore.value = null;
  };

  return {
    cartItems,
    currentStore,
    totalItems,
    totalAmount,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    setCurrentStore,
    clearCurrentStore
  };
}); 